﻿using Ducu.BLL.Entity;
using Ducu.SRV.ServiceInteface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ducu.SRV.Query;
using Global.Core.ExtensionMethod;
using System.Web;
using Ducu.GLB.Global;
using Ducu.SRV.ViewModel.Log;

namespace Ducu.SRV.ProdService
{
    public class LogService : BaseService, ILogService
    {
        public void On(ViewModel.Log.OnModel model, int? days)
        {
            //get the user id
            Register register = repoFactory.Query<Register>()
                .GetPassword(model.UserName).SingleOrDefault();

            if (register == null)
            {
                throw new Exception(
                    "try to logon with nonexistent username:" + model.UserName);
            }

            if (register.Password != model.Password.Md5Encypt())
            {
                throw new Exception(
                    "user " + model.UserName + " try to logon with incorrect password");
            }

            //put the user id and other auth info into cookie
            HttpCookie cookie = new HttpCookie(CookieName.USER_ID, register.User.Id.ToString());
            cookie.Values.Add(CookieName.AUTH_CODE, register.AuthCode.Md5Encypt());
            if (days.HasValue)
            {
                cookie.Expires = DateTime.Now.AddDays(days.Value);
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public void Off()
        {
            if (HttpContext.Current.Request.Cookies[CookieName.USER_ID] != null)
            {
                HttpCookie myCookie = new HttpCookie(CookieName.USER_ID);
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                HttpContext.Current.Response.Cookies.Add(myCookie);
            }
        }


        public bool HasPassed(OnModel model)
        {
            //get the user id
            Register register = repoFactory.Query<Register>()
                .GetPassword(model.UserName).SingleOrDefault();

            return model.Password.Md5Encypt() == register.Password;
        }
    }
}
